<template> 
	<div>
		<el-upload :action="localUploadUrl" :list-type="listType" multiple :headers="headers" :file-list="fileList"
			:before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess"
			:on-preview="handlePreview" :limit="maxCount" :on-exceed="handleExceed">
			<i class="el-icon-plus"></i>
		</el-upload>
		<el-dialog append-to-body :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>
<script>
	import {
		getToken,
	} from '@/utils/auth'
	export default {
		name: 'multiUploadLocal',
		props: {
			//图片属性数组
			value: Array,
			//最大上传图片数量
			maxCount: {
				type: Number,
				default: 99
			},
			isPrivate: {
				type: Boolean,
				default: false
			},
			listType: {
				type: String,
				default: 'picture-card'
			},
			fileSize: {
				type: Number,
				default: 5
			},
		},
		data() {
			return {
				dialogVisible: false,
				dialogImageUrl: null,
				localUploadUrl: process.env.BASE_API + (this.isPrivate ? '/file/uploadPrivate' : '/file/upload'),
				headers: {
					Authorization: getToken(),
				}
			};
		},
		computed: {
			fileList() {
				let fileList = [];
				for (let i = 0; i < this.value.length; i++) {
					fileList.push({
						url: this.value[i]
					});
				}
				return fileList;
			}
		},
		methods: {
			httpRequest(param) {
				let file = param.file;
				let formData = new FormData();
				formData.append("file", file);
			},
			beforeUpload(file) {
				let types = ['image/jpeg', 'image/jpg', 'image/png'];
				const isImage = types.includes(file.type);
				if (!isImage) {
					this.$message.error('上传图片只支持JPG、JPEG、PNG格式!')
					return false
				}
				const isLt5M = file.size / 1024 / 1024 < this.fileSize
				if (!isLt5M) {
					this.$message.error('上传图片不能超过' + this.fileSize + 'M')
					return false
				}
				return true
			},
			emitInput(fileList) {
				let value = [];
				for (let i = 0; i < fileList.length; i++) {
					value.push(fileList[i].url);
				}
				this.$emit('input', value)
			},
			handleRemove(file, fileList) {
				for (let item of fileList) {
					item.url = item.response.data
				}
				this.emitInput(fileList);
			},
			handlePreview(file) {
				this.dialogVisible = true;
				this.dialogImageUrl = file.url;
			},
			handleUploadSuccess(res, file) {
				this.fileList.push({
					name: file.name,
					url: res.data
				});
				this.emitInput(this.fileList);
			},
			handleExceed(files, fileList) {
				this.$message({
					message: '最多只能上传' + this.maxCount + '张图片',
					type: 'warning',
					duration: 1000
				});
			},
		}
	}
</script>
<style>

</style>